package edu.wit.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import com.google.gson.JsonObject;
import edu.wit.common.constant.CacheConstants;
import edu.wit.common.constant.Constants;
import edu.wit.common.core.domain.R;
import edu.wit.common.redis.service.RedisService;
import edu.wit.common.utils.JwtUtils;
import edu.wit.common.utils.ServletUtils;
import edu.wit.common.utils.StringUtils;
import edu.wit.gateway.config.IgnoreWhiteProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 全局Filter，统一处理会员登录与外部不允许访问的服务
 * </p>
 *
 * @author qy
 * @since 2019-11-21
 */

/**
 * GlobalFilter的功能其实和GatewayFilter是相同的，只是GlobalFilter的作用域是所有的路由配置，而不是绑定在指定的路由配置上。
 * 多个GlobalFilter可以通过@Order或者getOrder()方法指定每个GlobalFilter的执行顺序，order值越小，GlobalFilter执行的优先级越高。
 * 注意，由于过滤器有pre和post两种类型，pre类型过滤器如果order值越小，那么它就应该在pre过滤器链的顶层，
 * post类型过滤器如果order值越小，那么它就应该在pre过滤器链的底层。
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private static final Logger log = LoggerFactory.getLogger(AuthGlobalFilter.class);
    private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Autowired
    private RedisService redisService;

    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> sops;

//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpRequest request = exchange.getRequest();
//        String path = request.getURI().getPath();
//        //昊广api接口，校验用户必须登录
//        if(antPathMatcher.match("/api/**/auth/**", path)) {
//            List<String> tokenList = request.getHeaders().get("token");
//            if(null == tokenList) {
//                ServerHttpResponse response = exchange.getResponse();
//                return out(response);
//            } else {
////                Boolean isCheck = JwtUtils.checkToken(tokenList.get(0));
////                if(!isCheck) {
//                    ServerHttpResponse response = exchange.getResponse();
//                    return out(response);
////                }
//            }
//        }
//        //内部服务接口，不允许外部访问
//        if(antPathMatcher.match("/**/inner/**", path)) {
//            ServerHttpResponse response = exchange.getResponse();
//            return out(response);
//        }
//        return chain.filter(exchange);
//    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();
        // 跳过不需要验证的路径
//        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
//            return chain.filter(exchange);
//        }
        System.out.println("url====" + url);
        if (url.equals("/admin/auth/login") || url.equals("/admin/acl/index/info") || url.equals("/admin/acl/index/menu") || url.equals("/admin/auth/logout")) {
            return chain.filter(exchange);
        }
        String token = getToken(exchange.getRequest());

//        System.out.println("token=" + token);
        if (StringUtils.isBlank(token)) {
            return setUnauthorizedResponse(exchange, "令牌不能为空");
        }
        String userStr = sops.get(getTokenKey(token));

//        System.out.println("userStr====" + userStr);
        if (StringUtils.isNull(userStr)) {
            return setUnauthorizedResponse(exchange, "登录状态已过期");
        }
        //autoType is not support.===>打开autotype功能
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        JSONObject obj = JSONObject.parseObject(userStr);

//        System.out.println("obj===" + obj);

        String userid = obj.getString("userid");
        String username = obj.getString("username");
        if (StringUtils.isBlank(userid) || StringUtils.isBlank(username)) {
            return setUnauthorizedResponse(exchange, "令牌验证失败");
        }

        // 设置过期时间
        redisService.expire(getTokenKey(token), EXPIRE_TIME);

        // 设置用户信息到请求
        ServerHttpRequest mutableReq = exchange.getRequest().mutate().header(CacheConstants.DETAILS_USER_ID, userid)
                .header(CacheConstants.DETAILS_USERNAME, ServletUtils.urlEncode(username)).build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

        return chain.filter(mutableExchange);
    }

    @Override
    public int getOrder() {
        return -200;
    }

    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 405);
        message.addProperty("data", "鉴权失败");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
//        String token = request.getHeaders().getFirst(CacheConstants.HEADER);
        List<String> token1 = request.getHeaders().get("token");

//        System.out.println("token===" + token1);
//        if (StringUtils.isNotEmpty(token))
//        {
//            token = token.replace(CacheConstants.TOKEN_PREFIX, "");
//        }
//        ServletUtils.getRequest().getHeader()
        return token1.get(0);
    }

    private String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    private Mono<Void> setUnauthorizedResponse(ServerWebExchange exchange, String msg) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.setStatusCode(HttpStatus.OK);

        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            return bufferFactory.wrap(JSON.toJSONBytes(R.fail(HttpStatus.UNAUTHORIZED.value(), msg)));
        }));
    }
}
